package org.fly4j.part1.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by 37284 on 2016/1/2.
 *
 * 读取配置文件的工具类
 */
public final class PropsUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtils.class);

    /**
     * 加载属性文件
     */
    public static Properties loadProps(String fileName){
        Properties properties = null;
        InputStream inputStream = null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            //配置文件不存在
            if (inputStream==null){
                throw  new FileNotFoundException(fileName + "file is not found");
            }

            properties = new Properties();
            properties.load(inputStream);
        }catch (IOException e){
            LOGGER.error("load proper file failure .");
        }finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("close inputstrean failure .",e);
                }
            }
            return properties;
        }
    }

    /**
     * 获取字符型  无默认值
     */
    public static String getString(Properties properties,String key){
        return getString(properties,key,"");
    }

    /**
     * 获取字符型数据  可指定默认值
     */
    public static String getString(Properties properties,String key,String defaultValue){
        String value = defaultValue;
        if(properties.containsKey(key)){
           value = properties.getProperty(key);
        }
        return value;
    }

}
